package cn.zhouixi.ws.controller;
import cn.zhouixi.ws.config.EndpointConfig;
import cn.zhouixi.ws.listener.SubscribeListener;
import cn.zhouixi.ws.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

@ServerEndpoint(value = "/websocket/{userId}",configurator = EndpointConfig.class)
@RestController
@Component
public class MyWebSocket {

    private static AtomicLong onlineCount = new AtomicLong();

    private static ConcurrentHashMap<Long, Session> webSocketMap = new ConcurrentHashMap<>();

    private Long userId ;

    @Autowired
    RedisMessageListenerContainer redisMessageListenerContainer;

    @Autowired
    RedisUtils redisUtils;

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Long userId) {

        if(webSocketMap.get(userId) != null) {
            // 清除异常关闭没有清除的登录数据
            onlineCount.decrementAndGet();
        }
        webSocketMap.put(userId, session);
        System.out.println("有新链接加入!当前在线人数为:\t" + onlineCount.incrementAndGet());
        System.out.println("session id : " + session.getId() + "----- userId : " + userId);
        SubscribeListener subscribeListener = new SubscribeListener();
        // 构造 用户数据
        subscribeListener.setSession(session,userId);
        redisUtils.put(userId.toString(),session.getId());
        //设置订阅topic
        redisMessageListenerContainer.addMessageListener(subscribeListener, new ChannelTopic("TOPIC_USERNAME"));
        this.userId = userId;
    }

    @OnClose
    public void onClose(Session session) {
        webSocketMap.remove(userId);
        System.out.println("有一链接关闭!当前在线人数为:\t" + onlineCount.decrementAndGet());
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println("新消息:" + message);
    }
}
